//
//  CustomeAlertViewController.swift
//  TestHHHHH
//
//  Created by 刘汤圆 on 2018/7/17.
//  Copyright © 2018年 刘汤圆. All rights reserved.
//

import UIKit
import SnapKit

public enum NormalAlertBtnCount {
    case one(oneBtnTitile:String)
    case two(leftBtnTitle:String, rightBtnTitle:String)
}

public enum ExplainAlertType {
    case explainMobile
    case explainCVV
    case explainValidDate
}

public typealias NormalAlertLeftBtnClick = (_ vc: UIViewController) -> Void
public typealias NormalAlertRightBtnClick = (_ vc: UIViewController) -> Void
public typealias UpdateVersionAlertUpdateClick = (_ vc: UIViewController) -> Void

open class CustomeAlertViewController: UIViewController {

    public var leftBtnClickClosure:NormalAlertLeftBtnClick = {_ in }
    public var rightBtnClickClosure:NormalAlertLeftBtnClick = {_ in }
    public var updateVersionClickClosure:UpdateVersionAlertUpdateClick = {_ in}
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
    }
    
    public init(alertBtnType: NormalAlertBtnCount, title: String, msg: String) {
        super.init(nibName: nil, bundle: nil)
        initNormalAlert(type: alertBtnType, title: title, message: msg)
    }
    
    public init(explainType: ExplainAlertType) {
        super.init(nibName: nil, bundle: nil)
        initExplainAlert(explainType: explainType)
    }
    
    public init(versionContent:String, isForceUpdate:Bool) {
        super.init(nibName: nil, bundle: nil)
        initVersionUpdateAlert(desc: versionContent, showCloseBtn: isForceUpdate)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: normal alert
    private func initNormalAlert(type: NormalAlertBtnCount, title: String, message: String) {
        
        if title.count < 1 && message.count < 1 { return }
        
        let containView = UIView()
        self.view.addSubview(containView)
        containView.backgroundColor = .white
        containView.layer.masksToBounds = true
        containView.layer.cornerRadius = 13
        containView.snp.makeConstraints { (make) in
            make.width.equalTo(270)
            make.height.equalTo(160)
            make.center.equalTo(self.view)
        }
        let seprator = UIView()
        containView.addSubview(seprator)
        seprator.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
        seprator.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.left.right.equalTo(containView)
            make.bottom.equalTo(containView.snp.bottom).offset(-45)
        }
        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.textColor = .black
        titleLabel.font = UIFont(name: "STHeitiSC-Medium", size: 17)
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        
        let messageLabel = UILabel()
        messageLabel.text = message
        messageLabel.textColor = UIColor(red: 74/255.0, green: 74/255.0, blue: 74/255.0, alpha: 1)
        messageLabel.font = UIFont.systemFont(ofSize: 14)
        messageLabel.textAlignment = .center
        messageLabel.numberOfLines = 0
        
        if title.count > 0 && message.count > 0 {
            containView.addSubview(titleLabel)
            containView.addSubview(messageLabel)
            titleLabel.snp.makeConstraints { (make) in
                make.left.equalTo(containView.snp.left).offset(10)
                make.right.equalTo(containView.snp.right).offset(-10)
                make.top.equalTo(containView.snp.top).offset(10)
                make.height.equalTo(40)
            }
            messageLabel.snp.makeConstraints { (make) in
                make.top.equalTo(titleLabel.snp.bottom).offset(5)
                make.left.equalTo(containView.snp.left).offset(20)
                make.right.equalTo(containView.snp.right).offset(-20)
            }
        } else if title.count > 0 {
            containView.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { (make) in
                make.left.equalTo(containView.snp.left).offset(20)
                make.right.equalTo(containView.snp.right).offset(-20)
                make.centerY.equalTo(containView.snp.centerY).offset(-40/2)
            }
        } else {
            containView.addSubview(messageLabel)
            messageLabel.snp.makeConstraints { (make) in
                make.left.equalTo(containView.snp.left).offset(20)
                make.right.equalTo(containView.snp.right).offset(-20)
                make.centerY.equalTo(containView.snp.centerY).offset(-40/2)
            }
        }
        
        switch type {
        case .one(let title):
            let rightBtn = UIButton(type: .custom)
            containView.addSubview(rightBtn)
            rightBtn.setTitle(title, for: .normal)
            rightBtn.setTitleColor(.black, for: .normal)
            rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
            rightBtn.snp.makeConstraints { (make) in
                make.right.equalTo(containView.snp.right).offset(-10)
                make.left.equalTo(containView.snp.left).offset(10)
                make.top.equalTo(seprator.snp.bottom)
                make.bottom.equalTo(containView.snp.bottom)
            }
        case .two(let leftTitle, let rightTitle):
            let line = UIView()
            containView.addSubview(line)
            line.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
            line.snp.makeConstraints { (make) in
                make.height.equalTo(45)
                make.width.equalTo(1)
                make.top.equalTo(seprator.snp.bottom)
                make.centerX.equalTo(containView.snp.centerX)
            }
            let leftBtn = UIButton(type: .custom)
            containView.addSubview(leftBtn)
            leftBtn.setTitle(leftTitle, for: .normal)
            leftBtn.setTitleColor(UIColor(red: 74/255.0, green: 74/255.0, blue: 74/255.0, alpha: 1), for: .normal)
            leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
            leftBtn.snp.makeConstraints { (make) in
                make.left.equalTo(containView.snp.left).offset(10)
                make.right.equalTo(line.snp.left)
                make.top.equalTo(seprator.snp.bottom)
                make.bottom.equalTo(containView.snp.bottom)
            }
            let rightBtn = UIButton(type: .custom)
            containView.addSubview(rightBtn)
            rightBtn.setTitle(rightTitle, for: .normal)
            rightBtn.setTitleColor(.black, for: .normal)
            rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
            rightBtn.snp.makeConstraints { (make) in
                make.right.equalTo(containView.snp.right).offset(-10)
                make.left.equalTo(line.snp.right)
                make.top.equalTo(seprator.snp.bottom)
                make.bottom.equalTo(containView.snp.bottom)
            }
        }
    }
    
    @objc func leftBtnClick() {
        closeAct()
        self.leftBtnClickClosure(self)
    }
    
    @objc func rightBtnClick() {
        closeAct()
        self.rightBtnClickClosure(self)
    }
    
    // MARK: explain alert
    private func initExplainAlert(explainType: ExplainAlertType) {
        switch explainType {
        case .explainMobile:
            setupExplainAlert(type: .explainMobile, title:"手机号说明", desc: "银行预留的手机号码是办理该银行卡时所填写的手机号码。没有预留、手机号忘记或者已停用，请联系银行客服更新处理。", img: nil)
        case .explainCVV:
            setupExplainAlert(type: .explainCVV, title:"CVV说明", desc: "CVV是打印在信用卡背面白条上方的数字最后三位。", img: UIImage(named: "CVV"))
        case .explainValidDate:
            setupExplainAlert(type: .explainValidDate, title:"有效期说明", desc: "有效期是打印在信用卡正面卡号下方，标准格式为月份在前，年份在后的一串数字。", img: UIImage(named: "validDate"))
        }
    }

    private func setupExplainAlert(type: ExplainAlertType, title:String, desc:String, img:UIImage?) {
       
        let containView = UIView()
        containView.backgroundColor = .white
        containView.layer.masksToBounds = true
        containView.layer.cornerRadius = 13
        self.view.addSubview(containView)
        containView.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
            make.width.equalTo(270)
            make.height.equalTo(type == .explainMobile ? 170: 260)
        }
        let titleLabel = UILabel()
        containView.addSubview(titleLabel)
        titleLabel.text = title
        titleLabel.textAlignment = .center
        titleLabel.textColor = .black
        titleLabel.font = UIFont(name: "STHeitiSC-Medium", size: 17)
        titleLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(containView)
            make.top.equalTo(containView.snp.top).offset(10)
            make.height.equalTo(25)
        }
        let imgView = UIImageView(image: img)
        containView.addSubview(imgView)
        imgView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.centerX.equalTo(containView.snp.centerX)
        }
        let descLabel = UILabel()
        containView.addSubview(descLabel)
        descLabel.text = desc
        descLabel.numberOfLines = 0
        descLabel.textAlignment = .left
        descLabel.textColor = UIColor(red: 155/255.0, green: 155/255.0, blue: 155/255.0, alpha: 1)
        descLabel.font = UIFont.systemFont(ofSize: 13)
        descLabel.snp.makeConstraints { (make) in
            make.left.equalTo(containView.snp.left).offset(25)
            make.right.equalTo(containView.snp.right).offset(-25)
            make.top.equalTo(imgView.snp.bottom).offset(img == nil ? 2 : 12)
        }
        let seprator = UIView()
        containView.addSubview(seprator)
        seprator.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
        seprator.snp.makeConstraints { (make) in
            make.left.right.equalTo(containView)
            make.height.equalTo(1)
            make.bottom.equalTo(containView.snp.bottom).offset(-45)
        }
        let closeBtn = UIButton(type: .custom)
        containView.addSubview(closeBtn)
        closeBtn.setTitle("知道了", for: .normal)
        closeBtn.setTitleColor(.black, for: .normal)
        closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        closeBtn.backgroundColor = .white
        closeBtn.addTarget(self, action: #selector(closeAct), for: .touchUpInside)
        closeBtn.snp.makeConstraints { (make) in
            make.left.equalTo(containView.snp.left).offset(5)
            make.right.equalTo(containView.snp.right).offset(-5)
            make.top.equalTo(seprator.snp.bottom).offset(2)
            make.bottom.equalTo(containView.snp.bottom).offset(-3)
        }
        
    }
    
    @objc func closeAct() {
        guard parent != nil else { return }
        willMove(toParentViewController: nil)
        removeFromParentViewController()
        view.removeFromSuperview()
    }
    
    // MARK: version update alert
    func initVersionUpdateAlert(desc: String, showCloseBtn: Bool) {
        let containView = UIView()
        self.view.addSubview(containView)
        containView.backgroundColor = .white
        containView.layer.masksToBounds = true
        containView.layer.cornerRadius = 13
        containView.snp.makeConstraints { (make) in
            make.center.equalTo(self.view.snp.center)
            make.width.equalTo(268)
            make.height.lessThanOrEqualTo(320)
            make.height.greaterThanOrEqualTo(240)
        }
        let downloadImg = UIImageView(image: UIImage(named: "version_download"))
        containView.addSubview(downloadImg)
        downloadImg.snp.makeConstraints { (make) in
            make.centerX.equalTo(containView.snp.centerX)
            make.top.equalTo(containView.snp.top).offset(15)
        }
        let label = UILabel()
        containView.addSubview(label)
        label.text = "亲，有新版本啦！"
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        label.textColor = .black
        label.snp.makeConstraints { (make) in
            make.left.right.equalTo(containView)
            make.top.equalTo(downloadImg.snp.bottom).offset(10)
            make.height.equalTo(32)
        }
        let textView = UITextView()
        containView.addSubview(textView)
        textView.isUserInteractionEnabled = false
        //通过富文本来设置行间距
        let paraph = NSMutableParagraphStyle()
        //将行间距设置为28
        paraph.lineSpacing = 10
        //样式属性集合
        let attributes = [kCTFontAttributeName:UIFont.systemFont(ofSize: 13),
                          kCTParagraphStyleAttributeName: paraph,
                          kCTForegroundColorAttributeName:UIColor(red: 155/255.0, green: 155/255.0, blue: 155/255.0, alpha: 1)]
        textView.attributedText = NSAttributedString(string: desc, attributes: attributes as [NSAttributedStringKey : Any])
        let rect = textView.attributedText.boundingRect(with: CGSize(width: (268-2*24) - textView.textContainer.lineFragmentPadding * 2 , height: 100), options: .usesLineFragmentOrigin, context: nil)
        var height = rect.size.height + textView.textContainer.lineFragmentPadding * 2 + 0.5
        if height <= 54 {
            height = 54
        } else if (height >= 135) {
            height = 135
        }
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(label.snp.bottom).offset(10)
            make.left.equalTo(containView.snp.left).offset(24)
            make.right.equalTo(containView.snp.right).offset(-24)
            make.height.equalTo(height)
        }
        let updateBtn = UIButton(type: .custom)
        containView.addSubview(updateBtn)
        updateBtn.backgroundColor = .black
        updateBtn.setTitle("立即更新", for: .normal)
        updateBtn.setTitleColor(UIColor(red: 208/255.0, green: 185/255.0, blue: 140/255.0, alpha: 1), for: .normal)
        updateBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        updateBtn.addTarget(self, action: #selector(updateVersionAct), for: .touchUpInside)
        updateBtn.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom).offset(10)
            make.left.equalTo(containView.snp.left).offset(38)
            make.right.equalTo(containView.snp.right).offset(-38)
            make.height.equalTo(30)
            make.bottom.equalTo(containView.snp.bottom).offset(-17)
        }
        if showCloseBtn {
            let closeBtn = UIButton(type: .custom)
            self.view.addSubview(closeBtn)
            closeBtn.setImage(UIImage(named: "version_close"), for: .normal)
            closeBtn.addTarget(self, action: #selector(closeAct), for: .touchUpInside)
            closeBtn.snp.makeConstraints { (make) in
                make.centerX.equalTo(self.view.snp.centerX)
                make.top.equalTo(containView.snp.bottom).offset(20)
                make.width.height.equalTo(40)
            }
        }
    }
    
    @objc func updateVersionAct() {
        
        self.updateVersionClickClosure(self)
    }
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
